﻿using Microsoft.AspNetCore.SignalR.Client;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApp_SignalR_Client
{
    public partial class txtRec : Form
    {
        private HubConnection _connection;
        public txtRec()
        {
            InitializeComponent();
           
        }

        private async Task SignalRConnectionAsync(string url)
        {
            var conBuilder = new HubConnectionBuilder();
            conBuilder.WithUrl(url);
            _connection = conBuilder.Build();
            _connection.ServerTimeout = TimeSpan.FromSeconds(8);
            _connection.HandshakeTimeout = TimeSpan.FromSeconds(10);

            CancellationToken tocken = new CancellationToken()
            {

            };
            await _connection.StartAsync();

            _connection.Closed += SignalCloseAsync;


            _connection.On<object>("ReciveUpdataeAsync", msg =>
            {
                this.Invoke(new Action(() =>
                {
                    txtRecv.AppendText($"{DateTime.Now} recv message :{msg}");
                }));
            });
        }



        private async Task SignalCloseAsync(Exception arg)
        {
            await Task.Delay(TimeSpan.FromSeconds(1));
            await _connection.StartAsync();
        }

        private void btnSendMsg_Click(object sender, EventArgs e)
        {
            try
            {
                _connection.InvokeAsync("WinformAPPAsync", "SignalRClient_Winform", txtSend.Text);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void btnLinkService_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtServerUrl.Text))
            {
                MessageBox.Show("退无效地址");
                return;
            }
            var task = SignalRConnectionAsync(txtServerUrl.Text.Replace(" ", ""));
            while (task.IsCompleted)
            {
                Application.DoEvents();
                Thread.Sleep(100);
            }

        }

        private void txtServerUrl_TextChanged(object sender, EventArgs e)
        {

        }
    }
}
